package br.mg.bhe.ftpobre.command;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTPSClient;

import br.mg.bhe.ftpobre.Main;
import br.mg.bhe.ftpobre.fs.RemoteFile;
import br.mg.bhe.ftpobre.gui.MainFrame;
import br.mg.bhe.ftpobre.log.FtpLogView;
import br.mg.bhe.ftpobre.util.LogUtil;
import br.mg.bhe.ftpobre.util.RemoteFileUtil;

/**
 * 
 * @author Aureliano
 */
public class DownloadCommand implements ICommand {

	private static final Logger logger = LogUtil.getLogger(DownloadCommand.class);
	
	@Override
	public void execute() {
		if (this.canExecute()) {
			this.doAction();
		}
	}

	@Override
	public boolean canExecute() {
		return ((RemoteFileUtil.getSelectedFile() != null) && (Main.getConnectionData().isConnected()));
	}

	private void doAction() {
		String localPath = MainFrame.getInstance().getAbsolutePathFromLocalFilePath();
		FTPSClient ftp = (FTPSClient) Main.getConnectionData().getFtpClient();
		
		try {
			String fileName = this.getDownloadCandidateFileName();
			FtpLogView.log("Iniciando download do arquivo '" + fileName + "' para a pasta '" + localPath + "'");
			
			String remotePath = MainFrame.getInstance().getAbsolutePathFromRemoteFilePath();
			ftp.retrieveFile(remotePath + "/" + fileName, this.getDownloadCandidateFileStream());
			
			FtpLogView.log("Arquivo '" + fileName + "' recebido com sucesso!");
			CommandFactory.command(RefreshLocalFilesViewCommand.class).execute();
		} catch (IOException ex) {
			logger.log(Level.SEVERE, ex.getMessage(), ex);
			FtpLogView.log("Não foi possível fazer download do arquivo. Detalhe: " + ex.getMessage());
			throw new RuntimeException(ex);
		}
	}
	
	private FileOutputStream getDownloadCandidateFileStream() throws FileNotFoundException {
		String localPath = MainFrame.getInstance().getAbsolutePathFromLocalFilePath();
		RemoteFile file = RemoteFileUtil.getSelectedFile();
		
		return new FileOutputStream(localPath + "/" + file.getFile().getName());
	}
	
	private String getDownloadCandidateFileName() {
		RemoteFile file = RemoteFileUtil.getSelectedFile();
		return file.getFile().getName();
	}
}